package logic

import (
	"context"
	"fmt"

	"mail/common/cryptx"
	"mail/service/account/model"
	"mail/service/account/rpc/account"
	"mail/service/account/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *account.RegisterRequest) (*account.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	//valid mobile is right
	_, err := l.svcCtx.AccountModel.FindOneByMobile(l.ctx, in.Mobile)
	if err == nil {
		return nil, status.Error(100, "account is exists.")
	}
	if err == model.ErrNotFound {
		newAccount := model.Account{
			Name:     in.Name,
			Gender:   in.Gender,
			Mobile:   in.Mobile,
			Password: cryptx.PasswordEncrypt(l.svcCtx.Config.Salt, in.Password),
		}
		fmt.Println(l.svcCtx.Config.Salt, newAccount.Password)
		res, err := l.svcCtx.AccountModel.Insert(l.ctx, &newAccount)
		if err != nil {
			return nil, status.Error(500, err.Error())
		}
		newAccount.Id, err = res.LastInsertId()
		if err != nil {
			return nil, status.Error(500, err.Error())
		}
		return &account.RegisterResponse{
			Id:     newAccount.Id,
			Name:   newAccount.Name,
			Gender: newAccount.Gender,
			Mobile: newAccount.Mobile,
		}, nil
	}

	return nil, status.Error(500, err.Error())
}
